package com.etc.controller;

import com.etc.pojo.User;
import com.etc.service.UserService;
import com.etc.util.PasswordUtil;
import com.zhenzi.sms.ZhenziSmsClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/UserController")
public class UserController {
@Autowired
    UserService service;
    ModelAndView modelAndView = new ModelAndView();
    /**
     * 注册用户
     * @param userName
     * @param password
     * @param phone
     * @param response
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/register")
    public void register(@RequestParam("userName") String userName, @RequestParam("password") String password,
                         @RequestParam("phone") String phone, HttpServletResponse response) throws IOException {
        String salt= PasswordUtil.salt();
        String md5Password= PasswordUtil.md5(password+salt);
        //新增用户
        User user = new User(userName, md5Password, salt, phone);

        boolean flag = service.register(user);
        User userGet = service.login(userName, md5Password);
        service.insertVipInfo(userGet.getUserId());

        if(flag) {
            response.getWriter().print("<script>location.href='../page/index1.jsp'</script>");
        }
    }
    @RequestMapping("/sendMs")
    //发送验证码功能
    private void sendMs(@RequestParam("phone") String phone,HttpServletResponse response) throws IOException {
        System.out.println(phone);
        ZhenziSmsClient client = new ZhenziSmsClient("https://sms_developer.zhenzikj.com", "109965", "2ce3169a-4dd3-4d71-86a8-a6289a45fea3");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("number",phone);
        params.put("templateId", "6706");
        String[] templateParams = new String[2];
        long l = Math.round((Math.random()+1) * 1000);
        String random = String.valueOf(l);

        templateParams[0] = random;
        templateParams[1] = "5分钟";
        params.put("templateParams", templateParams);
        try {
            String result = client.send(params);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        response.getWriter().print(random);

    }

    /**
     * 判断用户是否已经存在
     * @param userName
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/checkName",produces = "text/html;charset=utf-8")
    public String checkName(@RequestParam("userName") String userName){
        User  checkName= service.getQueryUserByUserName(userName);
        String flag="";
        if (checkName!=null ){
            flag="该用户名已存在，请换一个";
            return flag;
        }
        return flag="可用";
    }
    /**
     * 用户登录
     * @param userName
     * @param password
     * @param session
     * @return
     */

    @RequestMapping("/userLogin")
    public ModelAndView userLogin(@RequestParam(value = "userName",defaultValue = "") String userName, @RequestParam(value = "password",defaultValue = "") String password, HttpSession session){
        User userByUserName = service.getQueryUserByUserName(userName);
        if(userByUserName!=null){
            //获取密码
            String md5Password= PasswordUtil.md5(password+userByUserName.getSalt());
            User user = service.login(userName, md5Password);

            if (user==null){
                modelAndView.setViewName("forward:/login/userLogin.jsp");
            }else{
                //管理员页面
                if (user.getUserState()==1 && user.getUserLevel()==1){
                    session.setAttribute("user",user);

                    modelAndView.setViewName("forward:/frontbg/CenTer.jsp");
                }else if(user.getUserState()==1 && user.getUserLevel()==0){
                    //普通用户
                    session.setAttribute("user",user);
                    modelAndView.setViewName("redirect:/page/index1.jsp");
                }else {
                    modelAndView.setViewName("forward:/login/userLogin.jsp");
                }


            }

        }
        return modelAndView;
    }
    //前端退出
    @RequestMapping("/exit")
    @ResponseBody
    public void exit(HttpServletRequest request,SessionStatus sessionStatus){
        request.getSession().removeAttribute("user");
        sessionStatus.setComplete();
        /*return "forward:/page/index1.jsp";*/
    }
    //管理员登录
    @ResponseBody
    @RequestMapping("/UserAdmin")
    public ModelAndView UserAdmin(@RequestParam("userName") String userName, @RequestParam("password") String password, HttpSession session) {

        User queryAdminUserName = service.getQueryAdminUserName(userName);


        //获取密码
        String md5Pwd= PasswordUtil.md5(password+queryAdminUserName.getSalt());
        User user = service.adminLogin(userName, md5Pwd);

        if (user!=null && user.getUserState()!=0 && user.getUserLevel()==1){
            session.setAttribute("user",user);
            modelAndView.setViewName("forward:/page/index1.jsp");
        }else {
            modelAndView.setViewName("forward:/htai/login2.jsp");
        }
        return modelAndView;
    }
}
